<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Message } from '@element-plus/icons-vue'
import request from '@/utils/request'

const router = useRouter()

// 控制登录/注册状态
const isLoginMode = ref(true)

// 表单数据
const formData = reactive({
  username: '',
  name: '',
  password: '',
  confirmPassword: '',
  email: ''
})

// 清空表单函数
const clearForm = () => {
  formData.username = ''
  formData.name = ''
  formData.password = ''
  formData.confirmPassword = ''
  formData.email = ''
}

// 切换登录/注册模式
const toggleMode = () => {
  isLoginMode.value = !isLoginMode.value
  clearForm()
}

// 通过计算属性，根据当前是登录模式还是注册模式来返回不同的表单验证规则。
const rules = computed(() => {
  const baseRules = {
    userName: [
      { required: true, message: '请输入账号', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, message: '密码长度至少6位', trigger: 'blur' }
    ]
  }

  //  检查当前是否为注册模式（而非登录模式）
  if (!isLoginMode.value) {
    // 注册模式下的额外规则
    return {
      // 将基础验证规则展开到新对象中，相当于把confirmPassword和email拼接到baseRules中
      ...baseRules,
      //确认密码一致性
      confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== formData.password) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ],
      // 验证邮箱
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
      ]
    }
  }
  // 如果是登录模式，返回基础规则
  return baseRules
})

// 表单引用
const formRef = ref(null)

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    const valid = await formRef.value.validate()
    if (valid) {
      if (isLoginMode.value) {
        await userLogin()
      } else {
        await userRegister()
      }
    }
  } catch (error) {
    ElMessage.error('表单验证失败')
  }
}

// 用户登录方法
const userLogin = async () => {

  const data = await request.post('/user/login', {
    username: formData.username,
    password: formData.password
  })
  console.log(2222);
  console.log(data);

  if (data.token != null) {
    ElMessage.success('登录成功！')
    // 存储用户信息
    localStorage.setItem('token', data.token)
    localStorage.setItem('name', data.name)
    localStorage.setItem('icon', data.icon)
    localStorage.setItem('uid', data.uid)

    // 根据角色跳转
    data.userType === '1' ? router.push('/') : router.push('/userindex/index')
  } else {
    ElMessage.error(res.message || '登录失败！')
  }

}

// 用户注册方法
const userRegister = async () => {
  try {
    const data = await request.post('/user/register', {
      username: formData.username,
      password: formData.password,
      email: formData.email,
      name: formData.name
    })
    console.log(111);
    console.log(data);

    if (data) {
      ElMessage.success('注册成功！请登录')
      // 注册成功后切换到登录模式
      isLoginMode.value = true
      clearForm()
    } else {
      ElMessage.error(res.message || '注册失败！')
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '请求失败')
    console.error('注册请求错误:', error)
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}
</script>

<template>
  <div class="bg">
    <div class="login_container">
      <div class="img_container">
        <img src="@/assets/b.jpeg">
      </div>

      <el-form :rules="rules" ref="formRef" :model="formData" label-width="80px" class="login_form">
        <h2 class="form-title">{{ isLoginMode ? '用户登录' : '用户注册' }}</h2>

        <el-form-item label="账号" prop="username">
          <el-input size="small" v-model="formData.username" :prefix-icon="User"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input show-password size="small" v-model="formData.password" :prefix-icon="Lock"></el-input>
        </el-form-item>

        <!-- 注册模式下的额外字段 -->
        <template v-if="!isLoginMode">
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input show-password size="small" v-model="formData.confirmPassword" :prefix-icon="Lock"></el-input>
          </el-form-item>

          <el-form-item label="昵称" prop="name">
            <el-input size="small" v-model="formData.name" :prefix-icon="User"></el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input size="small" v-model="formData.email" :prefix-icon="Message"></el-input>
          </el-form-item>
        </template>

        <el-form-item class="btns">
          <el-button type="primary" size="small" round @click="submitForm">
            {{ isLoginMode ? '登录' : '注册' }}
          </el-button>
          <el-button type="info" round size="small" @click="resetForm">
            重置
          </el-button>
        </el-form-item>

        <div class="mode-toggle">
          <span @click="toggleMode" class="toggle-link">
            {{ isLoginMode ? '没有账号？立即注册' : '已有账号？立即登录' }}
          </span>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html,
body {
  height: 100%;
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

.bg {
  background: url('@/assets/login-bg.jpg') no-repeat center center fixed;
  background-size: cover;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.login_container {
  width: 380px;
  min-height: 450px;
  background-color: rgba(255, 249, 231, 0.95);
  border-radius: 15px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  position: relative;
  padding: 30px 25px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.img_container {
  width: 100px;
  height: 100px;
  background-color: #fff9e7;
  border-radius: 50%;
  padding: 12px;
  position: absolute;
  top: -50px;
  left: 50%;
  transform: translateX(-50%);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: center;
  align-items: center;
}

.img_container img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  background-color: #ffefcd;
}

.login_form {
  width: 100%;
  margin-top: 50px;
}

.form-title {
  text-align: center;
  margin-bottom: 25px;
  color: #333;
  font-weight: 600;
  font-size: 24px;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-form-item__label {
  font-weight: 500;
  color: #555;
}

.btns {
  margin-top: 10px;
  display: flex;
  justify-content: center;
  gap: 15px;
}

.el-button {
  width: 100px;
}

.mode-toggle {
  text-align: center;
  margin-top: 20px;
}

.toggle-link {
  color: #409EFF;
  cursor: pointer;
  font-size: 14px;
  transition: color 0.2s;
}

.toggle-link:hover {
  color: #67c23a;
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login_container {
    width: 90%;
    padding: 25px 20px;
  }

  .bg {
    padding: 15px;
  }
}
</style>